<?php
/**
 * 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_Controller_Action_Secure
 * @copyright  Copyright (c) 2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: Builder.php 7 2009-11-14 22:42:08Z nkeyes $
 */
class Bushido_Controller_Action_Builder extends Bushido_Controller_Action
{
	
	public function indexAction()
	{	
		$this->view->classTypes = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->fetchAll();
	}
	
	public function addAction()
	{
		$this->view->sourceForm = $this->_getSourceForm();
	}
	
	
	protected function _getSourceForm()
	{
		$form = new Bushido_Form();
		$form->addDecorator('HtmlTag', array('tag' => 'div', 'dojoType' => 'dojo.dnd.Source'));
		$fieldTypes = Bushido_Db_Table::getTable('Bushido_DbTable_FieldType')->fetchAll();
		
		foreach($fieldTypes as $fieldType)
		{
			$fieldTable = new Bushido_Db_Table_Generic(array('name' => $fieldType->field_table, 'sequence' => true));
			
			$metadata = $fieldTable->info('metadata');
			$fieldData = $metadata['value'];
			$subForm = new Bushido_Form_SubForm();
			$subForm->clearDecorators();
			
			$subForm->addDecorator('FormElements');
			$subForm->addDecorator('HtmlTag', array('tag' => 'div', 'class' => 'dojoDndItem'));
			$subForm->generateElement($fieldType->name, $fieldData);
			$form->addSubForm($subForm, $fieldType->name . '_subForm');
		}
		
		return $form;
	}
	
	public function saveAction()
	{
		$classTypeData = stripslashes($this->_getParam('classTypeData'));
		$classTypeId = $this->_getParam('class_type_id');
		$classTypeDataObj = Zend_Json_Decoder::decode($classTypeData);
		

		Bushido_Db_Table::getAdapter()->beginTransaction();
		try
		{
			if($classTypeId)
			{
				$newClass = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->find($classTypeId)->current();
				foreach($newClass->findBushido_DbTable_ClassFieldType() as $field)
				{
					$foundField = false;
					foreach($classTypeDataObj['fields'] as $order => $classFieldType)
					{
						if($field->field_type_2_class_type_id == $classFieldType['id'])
						{
							$foundField = true;
							break;
						}
					}
					if(!$foundField)
					{
						$field->delete();
					}
				}
			}
			else
			{
				$newClass = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->fetchNew();
			}
			$newClass->name = $classTypeDataObj['name'];
			$newClass->save();
			Zend_Debug::dump($classTypeData);
			Zend_Debug::dump($classTypeDataObj);
			foreach($classTypeDataObj['fields'] as $order => $classFieldType)
			{
				if($classFieldType['id'] && Bushido_Db_Table::getTable('Bushido_DbTable_ClassFieldType')->find($classFieldType['id'])->current())
				{
					$newClassFieldType = Bushido_Db_Table::getTable('Bushido_DbTable_ClassFieldType')->find($classFieldType['id'])->current();
					//Zend_Debug::dump($newClassFieldType);
				}
				else
				{
					$newClassFieldType = Bushido_Db_Table::getTable('Bushido_DbTable_ClassFieldType')->fetchNew();
				}
				
				$newClassFieldType->class_type_id = $newClass->class_type_id;
				$newClassFieldType->field_type_id = Bushido_Db_Table::getAdapter()->fetchOne('SELECT field_type_id from field_type where name = ?', $classFieldType['dataType']);
				$newClassFieldType->order = $order+1;
				$newClassFieldType->label = $classFieldType['label'];
				$newClassFieldType->save();
			}
			Bushido_Db_Table::getAdapter()->commit();
			$fallbackPage = Bushido_App::session()->fallbackPage;
			if($fallbackPage)
			{
				$this->_helper->redirector($fallbackPage['action'], $fallbackPage['controller'], $fallbackPage['module']);
			}
			else
			{
				$this->_helper->redirector('index');
			}
		}
		catch(Exception $e)
		{
			Bushido_Db_Table::getAdapter()->rollBack();
			throw $e;
		}
		
	}
	
	public function viewAction()
	{
		$classTypeId = $this->_getParam('class_type_id');
		$classType = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->find((int)$classTypeId)->current();
		$classTypeData = array
		(
			'id' => $classType->class_type_id,
			'name' => $classType->name,
			'fields' => array()
		);
		foreach($classType->findBushido_DbTable_ClassFieldType(Bushido_Db_Table::getTable('Bushido_DbTable_ClassFieldType')->select()->order('order ASC')) as $field)
		{
			$classTypeData['fields'][] = array
			(
				'id' => $field->field_type_2_class_type_id,
				'label' => $field->label,
				'dataType' => Bushido_Db_Table::getTable('Bushido_DbTable_FieldType')->find($field->field_type_id)->current()->name
			);
		}
		
		$this->view->classTypeData = Zend_Json_Encoder::encode($classTypeData);
	}
	
	public function addInstanceAction()
	{
		$classTypeId = $this->_getParam('class_type_id');
		$classType = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->find($classTypeId)->current();
		$this->view->classType = $classType;
		$form = Bushido_DbTable_ClassType::getInstanceForm($classType);

		if($this->getRequest()->isPost())
		{
			if($form->isValid($_POST))
			{
				Bushido_Db_Table::getAdapter()->beginTransaction();
				try
				{
					$classInstance = Bushido_Db_Table::getTable('Bushido_DbTable_ClassInstance')->fetchNew();
					$classInstance->class_type_id = $classTypeId;
					
					$classInstance->save();

					$classFieldTypes = $classType->findBushido_DbTable_ClassFieldType(Bushido_Db_Table::getTable('Bushido_DbTable_ClassFieldType')->select()->order('order ASC'));
					foreach($classFieldTypes as $classFieldType)
					{			
						$instanceFieldValue = $form->getValue('field_type_2_class_type_' . $classFieldType->field_type_2_class_type_id);
						
						$instanceFieldTableName = Bushido_Db_Table::getAdapter()->fetchOne('SELECT name FROM field_type where field_type_id = ?', $classFieldType->field_type_id);
						$instanceFieldTable = new Bushido_Db_Table_Generic(array('name' => $instanceFieldTableName . '_field', 'sequence' => true));
						
						$instanceFieldValueRow = $instanceFieldTable->fetchNew();
						
						$instanceFieldValueRow->class_instance_id = $classInstance->class_instance_id;
						$instanceFieldValueRow->field_type_2_class_type_id = $classFieldType->field_type_2_class_type_id;
						$instanceFieldValueRow->value = $instanceFieldValue;
						
						$instanceFieldValueRow->save();
						
					}
					
					Bushido_Db_Table::getAdapter()->commit();
					
					$fallbackPage = Bushido_App::session()->fallbackPage;
					if($fallbackPage)
					{
						$this->_helper->redirector($fallbackPage['action'], $fallbackPage['controller'], $fallbackPage['module']);
					}
					else
					{
						$this->_helper->redirector('list-instances', null, null, array('class_type_id' => $classTypeId));
					}
				}
				catch(Exception $e)
				{
					Bushido_Db_Table::getAdapter()->rollBack();
					throw $e;
				}
			}
		}
		
		$form->addResetSubmit('Reset', 'Submit');
		
		$formActionParams = array('useLayout' => $this->_getParam('useLayout', 'true'));
		$formAction = $this->_helper->url($this->getRequest()->getActionName(), null, null, $formActionParams);
		$form->setAction($formAction);
		
		$this->view->form = $form;
	}
	
	public function viewInstanceAction()
	{
		$classTypeId = $this->_getParam('class_type_id');
		$classInstanceId = $this->_getParam('class_instance_id');
		$classType = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->find($classTypeId)->current();
		$classInstance = Bushido_Db_Table::getTable('Bushido_DbTable_ClassInstance')->find($classInstanceId)->current();
		$this->view->classType = $classType;
		$form = Bushido_DbTable_ClassType::getInstanceForm($classInstance);

		if($this->getRequest()->isPost())
		{
			if($form->isValid($_POST))
			{
				Bushido_Db_Table::getAdapter()->beginTransaction();
				try
				{
					$classFieldTypes = $classType->findBushido_DbTable_ClassFieldType(Bushido_Db_Table::getTable('Bushido_DbTable_ClassFieldType')->select()->order('order ASC'));
					foreach($classFieldTypes as $classFieldType)
					{			
						$instanceFieldValue = $form->getValue('field_type_2_class_type_' . $classFieldType->field_type_2_class_type_id);
						
						$instanceFieldTableName = Bushido_Db_Table::getAdapter()->fetchOne('SELECT name FROM field_type where field_type_id = ?', $classFieldType->field_type_id);
						$instanceFieldTable = new Bushido_Db_Table_Generic(array('name' => $instanceFieldTableName . '_field', 'sequence' => true));
						
						$instanceFieldValueRow = $instanceFieldTable->fetchAll($instanceFieldTable->select()->where('class_instance_id = ?', $classInstance->class_instance_id)->where('field_type_2_class_type_id = ?', $classFieldType->field_type_2_class_type_id))->current();
						if(!$instanceFieldValueRow)
						{
							$instanceFieldValueRow = $instanceFieldTable->fetchNew();
							$instanceFieldValueRow->class_instance_id = $classInstance->class_instance_id;
							$instanceFieldValueRow->field_type_2_class_type_id = $classFieldType->field_type_2_class_type_id;
						}
						$instanceFieldValueRow->value = $instanceFieldValue;
						
						$instanceFieldValueRow->save();
						
					}
					
					Bushido_Db_Table::getAdapter()->commit();
					
					$fallbackPage = Bushido_App::session()->fallbackPage;
					if($fallbackPage)
					{
						$this->_helper->redirector($fallbackPage['action'], $fallbackPage['controller'], $fallbackPage['module']);
					}
					else
					{
						$this->_helper->redirector('list-instances', null, null, array('class_type_id' => $classTypeId));
					}
				}
				catch(Exception $e)
				{
					Bushido_Db_Table::getAdapter()->rollBack();
					throw $e;
				}
			}
		}
		
		$form->addResetSubmit('Reset', 'Update');
		
		$formActionParams = array('useLayout' => $this->_getParam('useLayout', 'true'));
		$formAction = $this->_helper->url($this->getRequest()->getActionName(), null, null, $formActionParams);
		$form->setAction($formAction);
		
		$this->view->form = $form;
	}
	
	public function listInstancesJsonAction()
	{
		$this->_helper->layout->disableLayout();
		$classTypeId = $this->_getParam('class_type_id');
		
		$classInstances = Bushido_Db_Table::getTable('Bushido_DbTable_ClassInstance')->fetchAll(Bushido_Db_Table::getTable('Bushido_DbTable_ClassInstance')->select()->where('class_type_id = ?', $classTypeId));
		
		$dataArray = array();
		
		foreach($classInstances as $classInstance)
		{
			
			$dataArray[] = Bushido_DbTable_ClassType::getInstanceDataArray($classInstance);
			
		}
		//Zend_Debug::dump($dataArray);exit;
		$data = new Zend_Dojo_Data('class_instance_id', $dataArray);		
		$this->view->data = $data;
		
		
	}
	
	
	public function listInstancesAction()
	{
		$classTypeId = $this->_getParam('class_type_id');
		$classType = Bushido_Db_Table::getTable('Bushido_DbTable_ClassType')->find($classTypeId)->current();
		$this->view->classType = $classType;
	}

}